package org.hshk.message.mq;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.openservices.ons.api.*;
import com.aliyun.openservices.ons.api.bean.ProducerBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;

import java.util.UUID;

/**
 * Created With IntelliJ IDEA
 * User: WangYong
 * Date: 2017/2/25 0024
 * Time: 09:38
 * ProjectName: msgCenterAPI
 * 短信平台消息生产者
 */
@Component
@RefreshScope
public class MQProducer
{
    @Autowired
    private ProducerBean producer;
    //消息装载者
    private static Message msg;
    //日志记录类
    private static final Logger log = LoggerFactory.getLogger(MQProducer.class);
    
    @Value("${MQ_TOPIC_ID}")
    private String MqTopicId;
    @Value("${MQ_TOPIC_TAGS}")
    private String MqTopicTags;
    
    public void sendMessage(JSONObject param)
    {
        try {
            msg = new Message(MqTopicId,  //Topic 配置参数读取
                    MqTopicTags,//Tags 配置参数读取
                    "Hello World".getBytes());//此处是随意配置，主要是为了初始化
            String messageBody = param.toJSONString();
            //检测是否已经打开了消息的生产者
            if (producer.isClosed()) {
                producer.start();
            }
            //首先序列化数据
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            //Message Id 信息的唯一标识
            msg.setKey(uuid);
            //Message Body 信息的载体
            msg.setBody(messageBody.getBytes());
            //插入时间戳
            msg.setStartDeliverTime(System.currentTimeMillis());
            //加入队列，等待处理
            producer.sendAsync(msg, new SendCallback() {
                @Override
                public void onSuccess(SendResult sendResult) {
                    
                }

                @Override
                public void onException(OnExceptionContext context) {

                }
            });
            log.info(" ALiMQProducer 生产数据成功 [ messageKey : " + uuid + ", +  messageId : " + msg.getMsgID()
                    + ", +  messageBody : " + messageBody + " ]");
        }catch(Exception ex)
        {
            ex.printStackTrace();
            log.info(" ALiMQProducer 生产数据失败 [ messageKey : " + ex.getMessage() + " ]");
        }
    }
}